<template>
  <div class="create-page">
    <div class="warp">
      <input class="g-name" name="g-name" placeholder="团购名称" v-model="groupInfo.name" />
      <textarea class="g-info" placeholder="团购信息......" v-model="groupInfo.info" />
      <div class="img-group">
        <div class="img-list">
          <div class="item" v-for="item in imgList" :key="item">
            <img src="/static/img/remove_img.png" class="removeBtn" @click="removeImg(item)">
            <img :src="item" mode="aspectFill">
          </div>

          <div class="item btnAdd" @click="selectImg" v-show="addIsShow">
            <img src="/static/img/btn_addimg.png" mode="aspectFit">
          </div>
        </div>
      </div>

      <h3 class="block-title">商品</h3>
      <div class="block" v-for="(item, index) in productList" :key="index">
        <img class="remove-this" src="/static/img/btn_remove.png" mode="aspectFit" v-show="removeProductShow" @click="removeThis(index)" />
        <div class="name item">
          <strong>名称</strong>
          <input class="pname" placeholder="名称" v-model="item.title">
        </div>
        <div class="price item">
          <strong>价格</strong>
          <input class="price" type="number" placeholder="价格" v-model="item.price">
        </div>
      </div>
      <div class="addProduct iconfont" @click="addProduct" >&#xe6df; 添加商品</div>

      <div class="endTime">
        <div class="kg">
          <span class="stop">自动截止</span>
          <switch @change="autoComplete" :checked="endTimeShow"/>
        </div>
        <div class="time" v-show="endTimeShow">
          <span class="st">截止时间</span>
          <picker mode="date" :value="selectTime" :start="startTime" @change="bindTimeChange">
            <div class="iconfont stime">
              {{selectTime}} &#xe600;
            </div>
          </picker>
        </div>
      </div>
    </div>
    <div class="btn-create" @click="submit">
      <p>确认</p>
      <img src="/static/img/btn_back.png">
    </div>
  </div>
</template>

<script>
import { host } from '@/utils/conf'
import { latterTime, imagesLink, timeStamp, userLogin } from '@/utils/index'
export default {
  name: '',
  data () {
    return {
      query: {},
      imgList: [],
      productId: [],
      productList: [],
      startTime: '',
      selectTime: '',
      endTimeShow: false,
      groupInfo: {
        name: '',
        info: '',
      }
    }
  },
  computed: {
    addIsShow () {
      if (this.imgList.length >= 5) {
        return false
      } else {
        return true
      }
    },
    removeProductShow () {
      if (this.productList.length > 1) {
        return true
      } else {
        return false
      }
    },
    sendImg () {
      var res = []
      this.imgList.forEach(function(item, index) {
        var i = item.split('/')
        res.push(i[i.length-1])
      })
      return res;
    }
  },
  methods: {
    async requestData () {
      var that = this

      wx.showToast({
        icon: 'loading',
        duration: 50000,
        title: '请求中...'
      })
      //请求当前id的团购
      var res = await this.$request({
        url: '/GroupBuyBackendV1/groupBuyInfo/'+ that.query.groupId
      })
      that.groupInfo.name = res.title
      that.groupInfo.info = res.description
      if (res.dueDatetime && that.query.type == 'update') {
        that.endTimeShow = true
        that.selectTime = timeStamp(res.dueDatetime)
      }
      that.imgList = imagesLink(res.images.split(','))
      //通过productList获取产品信息
      var productList = res.productList.split(',')
      for (var i = 0; i < productList.length; i++) {
        var plist = await this.$request({
          url: '/GroupBuyBackendV1/product/' + productList[i]
        })
        that.productList.push(plist)
      }
      wx.hideToast()
    },
    verifyProduct () {
      for (var index in this.productList) {
        if (!this.productList[index].title || !this.productList[index].price) {
          wx.showToast({
            icon: 'none',
            title: '商品名称和价格需填写完整',
          })
          return false
        }
      }
      return true
    },
    verifyGroup () {
      var message = ''
      var isFalse = true

      if (this.imgList.length == 0) {
        isFalse = false
        message = '请添加商品图片！'
      }

      if (!this.groupInfo.info) {
        isFalse = false
        message = '请填写团购信息！'
      }

      if (!this.groupInfo.name) {
        isFalse = false
        message = '请填写团购名称！'
      }

      if (!isFalse) {
        wx.showToast({
          icon: 'none',
          title: message
        })
      }

      return isFalse;
    },
    addProduct () {
      if (this.verifyProduct()) {
        const p2 = {title: '', price: '', key: 1}
        this.productList.push(p2);
      }
    },
    removeThis (ins) {
      var that = this
      that.productList.forEach(function(item,index) {
        if (ins == index) {
          that.productList.splice(ins, 1)
        }
      })
    },
    selectImg () {
      var that = this;
      var count = 5;
      wx.chooseImage({
        count: count,
        sizeType: 'compressed',
        success: function (res) {
          //如果选择图片超过5张
          if (that.imgList.length && (that.imgList.length + res.tempFilePaths.length > count)) {
            res.tempFilePaths.length = imgCount - that.imgList.length
          }
          that.uploadFile(res.tempFilePaths)
        }
      })
    },
    removeImg (pic) {
      if (pic) {
        for (var i in this.imgList) {
          if (this.imgList[i] == pic) {
            this.imgList.splice(i, 1)
          }
        }
      }
    },
    autoComplete (e) {

      this.endTimeShow = !this.endTimeShow;
      // console.log(e.target.value)
    },
    bindTimeChange (e) {
      this.selectTime = e.target.value
    },
    //上传图片
    uploadFile (imgArr) {
      var that = this;
      if (imgArr && imgArr.length > 0) {
        wx.uploadFile({
          url: host + '/GroupBuyBackendV1/api/uploadFile',
          filePath: imgArr[0],
          name: 'file',
          header: { 'content-type': 'multipart/form-data'},
          success (res) {
            that.imgList.push(`${host + '/wetousuPhoto/'}${res.data}`)
            imgArr.splice(0, 1)
            that.uploadFile(imgArr);
          },
          fail () {
            wx.showToast({
              icon: 'none',
              title: '图片上传失败，请稍后再试'
            })
          }
        })
      }
    },
    //创建订单
    async submit () {
      if (this.verifyGroup() && this.verifyProduct()) {
        //上传商品信息
        var data = {}
        var that = this
        this.productId = []
        
        //创建商品
        for (var i = 0; i < this.productList.length; i++) {
          var item = this.productList[i]
          var pinfo = {
            title: item.title,
            price: item.price,
            userId: wx.getStorageSync('userId')
          }
          //如果有id的话则为更新
          if (item.productId) {
            pinfo.productId = item.productId
          }
          var cp = await this.$request({
            type: 'POST',
            url: '/GroupBuyBackendV1/product',
            data: pinfo
          })
          
          this.productId.push(cp.productId)
        }
       
        //最后创建订单
        wx.showToast({
          icon: 'loading',
          title: '请求中...',
          duration: 50000
        })
   
        var orderData = {
          status: '开团中',
          preStatus: '开团中',
          title: that.groupInfo.name,
          description: that.groupInfo.info,
          images: that.sendImg.join(','),
          createTime: new Date().getTime(),
          productList: that.productId.join(','),
          createUserId: wx.getStorageSync('userId'),
          dueDatetime: that.endTimeShow ? that.selectTime : ''
        }
        //更新需要传gid
        if (this.query.type== 'update') {
          orderData.groupId = this.query.groupId
        }
     
        var createOrder = await this.$request({
          url: '/GroupBuyBackendV1/groupBuyInfo',
          type: 'POST',
          data: orderData
        })
        wx.hideToast();
        //创建完成跳转到参团页
        if (createOrder.groupId) {
          wx.navigateTo({
            url: '/pages/group-detail/main?newCreate=1&groupId=' + createOrder.groupId
          })
        }
      }
    },
    clear () {
      this.query = {}
      this.imgList = []
      this.productId = []
      this.startTime = ''
      this.selectTime = ''
      this.productList = []
      this.endTimeShow = false
      this.groupInfo = {
        name: '',
        info: ''
      }
    }
  },
  mounted () {
    userLogin()
    this.clear()
    this.endTimeShow = false
    this.query = this.$root.$mp.query
    this.startTime = latterTime(0)
    if (this.query.type == 'update') {
      this.selectTime = ''
    } else {
      this.selectTime = latterTime(7)
    }
    this.requestData()
  },
  onUnload () {
    this.clear()
  }
}
</script>

<style lang="stylus" scoped>
  .create-page {
    padding-bottom: 100rpx
    .img-list {
      &:after {
        content: ''
        display: block
        width: 0
        height: 0
        clear: both
      }
      .item {
        width: 114rpx
        height: 114rpx
        float: left
        position: relative;
        img {
          width: 114rpx
          height: 114rpx
          border-radius: 20rpx
        }
        .removeBtn {
          width: 38rpx
          height: 38rpx
          position: absolute
          right: -12rpx
          top: -12rpx
        }
      }
      .item + .item{
        margin-left: 28rpx
      }
    }
    .warp {
      padding: 12rpx 32rpx
    }
    .g-name {
      height: 96rpx
      line-height: 96rpx
      font-size: 34rpx
    }
    .g-info {
      font-size: 28rpx
      padding-top: 20rpx
      width: 100%
      height: 130rpx
      border-top: 1px solid #f4f4f4
    }
    .img-group {
      margin-top: 10rpx
      .btnAdd {
        img {
          height: 114rpx
          width: 114rpx
        }
      }
    }
    .block-title {
      color: #131313
      font-size: 34rpx
      margin-top: 52rpx
      line-height: 80rpx
    }

    .block {
      border-top: 1px solid #f4f4f4
      font-size: 26rpx
      overflow: hidden
      padding: 10rpx 0
      position: relative
      .remove-this {
        width: 42rpx
        height: 42rpx
        position: absolute
        right: 3rpx
        top: 20rpx
        z-index: 10
      }
      .item {
        overflow: hidden
        font-size: 28rpx
        vertical-align: middle
        strong {
          float: left
          height: 62rpx
          line-height: 62rpx
          margin-right: 40rpx
        }
        input {
          height: 62rpx
          line-height: 62rpx
        }
      }
    }
    .addProduct {
      color: #576b95
      text-align: center
      font-size: 28rpx
    }
    .endTime {
      margin-top: 30rpx
      padding-top: 25rpx
      border-top: 1px solid #f4f4f4
      .kg {
        overflow: hidden
      }
      .stop {
        float: left
        font-size: 36rpx
        color: #131313
        line-height: 65rpx
      }
      switch {
        float: right
      }
      .time {
        color: #131313
        margin-top: 22rpx
        font-size: 28rpx
        .st {

        }
        picker {
          float: right
        }
        .stime {

        }
      }
    }
    .btn-create {
      width: 100%
      bottom: 0
      left: 0
      background: #fff
      position: fixed
      z-index: 1000
      img {
        height: 94rpx
        width: 100%
      }
      p {
        color: #fff
        position: absolute
        width: 100%
        height: 94rpx
        text-align: center
        line-height: 94rpx
        left: 0
        top: 0
      }
    }
  }

</style>
